﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using MensUnoShop.Models;
using MensUnoShop.Models.ViewModels;
using MensUnoShop.Filters;
using SenerPro;
using System.Xml.Linq;


namespace MensUnoShop.Controllers
{
    public class MarketController : Controller
    {
        //
        // GET: /Market/
        private string[] _view = new string[] { "", "mainDepartment", "subDepartment", "n"};
        private Member _member;
        private List<Tag> _toptaglist,_navlist,_leftlist;
        private string _title;
        private List<UNews> _newslist;
        private XElement _hotkeylist;

        public MarketController()
        {
            _member = MemberFactory.GetMember();
            _toptaglist = TagFactory.GetTopTagList();
            _newslist = NewsFactory.GetNewsList();
            _hotkeylist = KeyWordFactory.GetHotKeyList();
        }

        [NormalMarketFilter]
        public ActionResult n(string mksn, string pdtag, int tagid)
        {
            Tag current = (Tag)ViewData["currenttag"];
            _navlist = (List<Tag>)ViewData["navlist"];
            NormalMarket mk = (NormalMarket)ViewData["market"];
            var pd = mk.PRODUCTLIST.SingleOrDefault(p => p.TITLETAGID == int.Parse(pdtag));
            pd.GetSpecification();
            _leftlist = TagFactory.GetLeftTagList(current.PARENTID);
            Session["spec"] = mk.STANDARDS;
            Session["note"] = mk.WASHNOTE;
            MarketViewModel mvm = new MarketViewModel()
            {
                LEFTTAG = _leftlist,
                MARKET = mk,
                MEMBER = _member,
                PRODUCT = pd,
                NAVLIST = _navlist,
                TITLE = _title,
                TOPLIST = _toptaglist,
                NEWS=_newslist,
                HOTKEYLIST = _hotkeylist
            };
            return View(mvm);
        }

        [ComboMarketFilter]
        public ActionResult combo(string mksn, string pdtag, int tagid)
        {
            Tag current = (Tag)ViewData["currenttag"];
            _navlist = (List<Tag>)ViewData["navlist"];
            NormalMarket mk = (NormalMarket)ViewData["market"];
            var pd = mk.PRODUCTLIST.SingleOrDefault(p => p.TITLETAGID == int.Parse(pdtag));
            pd.GetSpecification();
            _leftlist = TagFactory.GetLeftTagList(current.PARENTID);
            Session["spec"] = mk.STANDARDS;
            Session["note"] = mk.WASHNOTE;
            List<TinyMarket> combomarketlist = new List<TinyMarket>();
            ViewData["combomarketlist"] = combomarketlist;
            MarketViewModel mvm = new MarketViewModel()
            {
                LEFTTAG = _leftlist,
                MARKET = mk,
                MEMBER = _member,
                PRODUCT = pd,
                NAVLIST = _navlist,
                TITLE = _title,
                TOPLIST = _toptaglist,
                NEWS = _newslist,
                HOTKEYLIST = _hotkeylist
            };
            return View(mvm);
        }

        [MagazineMarketFilter]
        public ActionResult maga(string id)
        {
            Tag current = (Tag)ViewData["currenttag"];
            _navlist = (List<Tag>)ViewData["navlist"];
            MagazineMarket mk = (MagazineMarket)ViewData["market"];
            var pd = mk.PRODUCTLIST.First();
            pd.GetSpecification();
            _leftlist = TagFactory.GetLeftTagList(current.PARENTID);
            MarketViewModel mvm = new MarketViewModel()
            {
                LEFTTAG = _leftlist,
                MARKET = mk,
                MEMBER = _member,
                PRODUCT = pd,
                NAVLIST = _navlist,
                TITLE = _title,
                TOPLIST = _toptaglist,
                NEWS = _newslist,
                HOTKEYLIST = _hotkeylist
            };
            return View(mvm);
        }

        public ActionResult magazine()
        {
            _leftlist = TagFactory.GetLeftTagList(1);
            RegionViewModel _iv = new RegionViewModel { MEMBER = _member, TITLE = _title, TOPLIST = _toptaglist, LEFTTAG = _leftlist };
            return View(_iv);
        }

        //購物車
        [NoCacheFilter]
        public ActionResult c(string id)
        {
            if (id == null)
            {
                if (Request.Cookies["scguid"] != null)
                    id = Request.Cookies["scguid"].Value;
            }
            if (id != null)
            {
                //設定view的內容
                ViewData["scguid"] = id;
                ShoppingCart sc = ShoppingCart.GetShoppingCart();
                if (sc.MLIST.Count > 0)
                {
                    CartViewModel nmv = new CartViewModel()
                    {
                        MEMBER = _member,
                        CART = sc,
                        TOPLIST = _toptaglist
                    };
                    return View(nmv);
                }
                else
                {
                    string uri = Request.UrlReferrer == null ? "/" : (Request.UrlReferrer.AbsolutePath==Request.Url.AbsolutePath||Request.UrlReferrer.AbsolutePath.Contains("order"))?"/":Request.UrlReferrer.ToString();
                    return View("ErRedirect", new ErrorViewModel() { ALERT = "購物車目前沒有任何商品，請您先找到想要購買之商品~", URI = uri });
                }
            }
            else
            {
                string uri = Request.UrlReferrer == null ? "/" : (Request.UrlReferrer.AbsolutePath == Request.Url.AbsolutePath || Request.UrlReferrer.AbsolutePath.Contains("order")) ? "/" : Request.UrlReferrer.ToString();
                return View("ErRedirect", new ErrorViewModel() { ALERT = "購物車目前沒有任何商品，請您先找到想要購買之商品~", URI = uri });
            }
        }

        //購物車
        [HttpPost]
        public ActionResult c(string utype, Guid mokguid, string values)
        {
            string response = string.Empty;
            ShoppingCart sc = ShoppingCart.GetShoppingCart();
            
            switch (utype)
            { 
                case "addfavorite":
                    break;
                case "setamount":
                    int a = 0;
                    int.TryParse(values, out a);
                    if (a > 0)
                        if (sc.SetMarketAmount(mokguid, a))
                            response = "數量變更成功";
                        else
                            response = "庫存不足!";
                    else
                        response = "請輸入正確數字!";
                    break;
                case "del":
                    sc.Remove(mokguid);
                    response = "賣場移除成功";
                    break;

            }

            TempData["alert"] = response;

            return RedirectToAction("c");
            //return View("ErRedirect", new ErrorViewModel() { ALERT = response, URI = "/market/c" });
            
        }

        public ActionResult mailtofriend(string id)
        {
            NormalMarket nm = new NormalMarket();
            nm = MarketFactory.GetNormalMarket(id);

            ViewData["TITLE"] = nm.TITLE;
            ViewData["IMG"] = nm.IMG;
            ViewData["MarketUri"] = nm.GetMarketUri();

            return View(nm);
        }

        public ActionResult light(string id)
        {
            string memo = string.Empty;
            try
            {
                memo = Session[id].ToString();
            }
            catch { }
            Response.Clear();
            Response.Write(memo);
            return View();
        }

        [HttpPost]
        public string mailtofriend()
        {
            string femail = Request.Params["femail"];
            string fname = Request.Params["fname"];
            string memail = Request.Params["memail"];
            string mname = Request.Params["mname"];
            string pname = Request.Params["pname"];
            string memo = Request.Params["memo"];
            string pimg = Request.Params["pimg"];
            string plink = Config.Site + Request.Params["plink"];

            if (femail != string.Empty && fname != string.Empty && memail != string.Empty && mname != string.Empty)
            {
                //發送好友推薦通知信
                string mailcontent = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(Config.Latter_Mail_To_Friend)).Replace("[fname]", fname).Replace("[mname]", mname).Replace("[pname]", pname).Replace("[pimg]", pimg).Replace("[plink]", plink);
                Config.SendMail("好友推薦信", mailcontent, femail, fname);                
                return "已寄信給您的朋友囉";
            }
            else
            {               
                return "資料不完整唷!";
            }
            
        }

    }
}
